import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { message, Button, Popconfirm } from 'antd'
import {
  EditFilled,
  PlusCircleFilled,
  DeleteFilled,
  ClockCircleOutlined,
  EditOutlined,
} from '@ant-design/icons'
import PubSub from 'pubsub-js'
import store from '@/redux/store'
import styles from './index.module.less'
import { getHarvestExamplesApi } from '@/request/api/harvest'
import { getExampleNoteListApi, deleteExampleApi } from '@/request/api/example'
import { deleteNoteApi } from '@/request/api/notes'
import MarkdownViewer from '@/components/MarkdownViewer'

export default function Read() {
  const [projectId, setProjectId] = useState<string>(
    store.getState().harvestInfoReducer.projectId
  )
  const [harvestId, setHarvestId] = useState<string>(
    store.getState().harvestInfoReducer.harvestId
  )
  const [description, setDescription] = useState<string>(
    store.getState().harvestInfoReducer.description
  )

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setProjectId(store.getState().harvestInfoReducer.projectId)
      setHarvestId(store.getState().harvestInfoReducer.harvestId)
      setDescription(store.getState().harvestInfoReducer.description)
    })

    return () => {
      unsubscribe()
    }
  }, [])

  useEffect(() => {
    if (harvestId) getHarvestExamples(harvestId)
  }, [harvestId])

  const navigate = useNavigate()
  // 示例列表
  const [exampleList, setExampleList] = useState<getExampleResultItf[]>([])

  // 获取收获示例列表
  const getHarvestExamples = async (id: string) => {
    const { code, data } = await getHarvestExamplesApi(id)

    if (code === 200) {
      PubSub.publish('scrollWindow')
      return setExampleList(data)
    }

    setExampleList([])
    message.error('获取示例失败！')
  }

  // 删除示例
  const deleteExample = async (id: string) => {
    const res = await deleteExampleApi(id)
    if (res.code !== 200) return message.error('删除示例失败！')
    getHarvestExamples(harvestId)
    message.success('删除示例成功！')
  }

  return (
    <div className={styles.readContainer}>
      <div className={styles.label}>收获描述：</div>
      <div className={styles.description}>{description}</div>

      {exampleList.map((item) => {
        return (
          <div className={styles.example} key={item.id}>
            <div className={styles.divide}></div>

            <div className={styles.title}>
              <h4>示例：</h4>
              <Button
                type='primary'
                size='small'
                icon={<EditFilled />}
                onClick={() => navigate(`/edit/updateExample/${item.id}`)}
              >
                修改此示例
              </Button>
              <Button
                type='primary'
                size='small'
                icon={<PlusCircleFilled />}
                onClick={() => navigate(`/edit/createNote/${item.id}`)}
              >
                为此示例添加笔记
              </Button>

              <Popconfirm
                title='删除示例'
                description='你确定要删除这个示例吗？包括示例下的所有笔记'
                onConfirm={() => deleteExample(item.id)}
                okText='删除'
                cancelText='取消'
              >
                <Button size='small' danger icon={<DeleteFilled />}>
                  删除此示例笔记
                </Button>
              </Popconfirm>

              <div title='创建时间'>
                <ClockCircleOutlined style={{ fontSize: '18px' }} />
                &nbsp;
                {item.createTime.slice(0, 11)}
              </div>
              <div title='最近修改时间'>
                <EditOutlined style={{ fontSize: '18px' }} />
                &nbsp;
                {item.updateTime.slice(0, 11)}
              </div>
            </div>

            <MarkdownViewer markdownContent={item.content} />

            {/* 渲染示例笔记列表 */}
            <NoteList exampleId={item.id} />

            <div className={styles.divide}></div>
          </div>
        )
      })}
    </div>
  )
}

//
// 笔记列表
function NoteList({ exampleId }) {
  const navigate = useNavigate()

  useEffect(() => {
    getExampleNoteList(exampleId)
  }, [exampleId])

  const [noteList, setNoteList] = useState<getNoteResultItf[]>([])

  // 获取示例笔记列表
  const getExampleNoteList = async (ids: string) => {
    const res = await getExampleNoteListApi(ids)
    if (res.code === 200) return setNoteList(res.data)

    setNoteList([])
    message.error('获取示例笔记失败！')
  }

  // 删除笔记
  const deleteNote = async (id: string) => {
    const res = await deleteNoteApi(id)
    if (res.code !== 200) return message.error('删除笔记失败！')
    getExampleNoteList(exampleId)
    message.success('删除笔记成功！')
  }

  return (
    <>
      {noteList.map((item) => {
        return (
          <div className={styles.noteItem} key={item.id}>
            <div className={styles.divide}></div>

            <div className={styles.title}>
              <h4>笔记：</h4>
              <Button
                type='primary'
                size='small'
                icon={<EditFilled />}
                onClick={() => navigate(`/edit/updateNote/${item.id}`)}
              >
                修改此示例笔记
              </Button>

              <Popconfirm
                title='删除笔记'
                description='你确定要删除这个笔记吗？'
                onConfirm={() => deleteNote(item.id)}
                okText='删除'
                cancelText='取消'
              >
                <Button size='small' danger icon={<DeleteFilled />}>
                  删除此示例笔记
                </Button>
              </Popconfirm>

              <div title='创建时间'>
                <ClockCircleOutlined style={{ fontSize: '18px' }} />
                &nbsp;
                {item.createTime.slice(0, 11)}
              </div>
              <div title='最近修改时间'>
                <EditOutlined style={{ fontSize: '18px' }} />
                &nbsp;
                {item.updateTime.slice(0, 11)}
              </div>
            </div>

            <MarkdownViewer markdownContent={item.content} />

            <div className={styles.divide}></div>
          </div>
        )
      })}
    </>
  )
}
